﻿using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using StockholmsStad.Runtime.Serialization.DataContract.Enums;
using StockholmsStad.Windows.UI.Modules.Maintenance.Interfaces;
using StockholmsStad.Windows.UI.Modules.Maintenance.Models;
using System.Collections.ObjectModel;
using StockholmsStad.Runtime.Serialization.DataContract;
using Microsoft.Practices.Composite.Events;

namespace StockholmsStad.Windows.UI.Modules.Maintenance.Views
{
    /// <summary>
    /// Interaction logic for TabItemTemplates.xaml
    /// </summary>
    public partial class TabItemTemplateView : ITemplatesView
    {
        private ObservableCollection<MarriageCertificateType> marriageCertificateTypes;
        private ObservableCollection<ValueIdPair> certificateLanguages;
        private ObservableCollection<ValueIdPair> allLanguages;
        private TemplatesPresentationModel model;
        private readonly ITempatesService templateService;

        public TabItemTemplateView(ITempatesService service)
        {
            templateService = service;

            InitializeComponent();
            Loaded += UserControl_Loaded;
            DataContextChanged += UserControl_DataContextChanged;
        }

        #region ITemplatesView Members

        public TemplatesPresentationModel Model
        {
            get { return DataContext as TemplatesPresentationModel; }
            set
            {
                var dataModel = value;
                dataModel.Saved += model_Saved;
                dataModel.Deleted += model_Deleted;
                DataContext = dataModel;
            }
        }

        #endregion

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            marriageCertificateTypes = templateService.GetMarriageCertificateTypes();
            ComboBoxAllLanguages.ItemsSource = allLanguages;
            ComboBoxMarriageCertificateTypes.ItemsSource = marriageCertificateTypes;

            //Om det bara finns en typ så välj den med automatik
            if (marriageCertificateTypes.Count == 1)
            {
                ComboBoxMarriageCertificateTypes.SelectedIndex = 0;
                GetLanguagesForCertificateType();
                ComboBoxMarriageCertificateLanguages.SelectedIndex = 0;
            }
        }

        private void model_Saved(object sender, DataEventArgs<TemplatesPresentationModel> e)
        {
            DataContext = e.Value;
            model = DataContext as TemplatesPresentationModel;

            if (ComboBoxMarriageCertificateLanguages.Visibility == Visibility.Visible && ComboBoxMarriageCertificateTypes.SelectedItem != null)
            {
                // Uppdatera listan med språk för ceremonityp, hack för att uppdatera selecteditem på listan över språk
                var langs = templateService.GetLanguagesForCertificateType(
                    (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem);
                ComboBoxMarriageCertificateLanguages.ItemsSource = langs;

                ComboBoxMarriageCertificateLanguages.SelectedIndex = FindItem(model.SelectedLanguage.Name);
            }
        }

        private void model_Deleted(object sender, DataEventArgs<TemplatesPresentationModel> e)
        {
            DataContext = e.Value;
            model = DataContext as TemplatesPresentationModel;

            if (ComboBoxMarriageCertificateLanguages.Visibility == Visibility.Visible && ComboBoxMarriageCertificateTypes.SelectedItem != null)
            {
                // Uppdatera listan med språk för ceremonityp, hack för att uppdatera selecteditem på listan över språk
                var langs = templateService.GetLanguagesForCertificateType(
                    (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem);
                ComboBoxMarriageCertificateLanguages.ItemsSource = langs;

                ComboBoxMarriageCertificateLanguages.SelectedIndex = 0;
            }
        }

        private int FindItem(string name)
        {
            for(int i = 0; i < ComboBoxMarriageCertificateLanguages.Items.Count; i++)
            {
                var item = (ValueIdPair)ComboBoxMarriageCertificateLanguages.Items[i];
                if(item.Name == name)
                    return i;
            }

            return -1;
        }

        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            model = DataContext as TemplatesPresentationModel;
        }

        private void ComboBoxMarriageCertificateTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetLanguagesForCertificateType();
        }

        private void GetLanguagesForCertificateType()
        {
            if (!model.MarriageCertificateId.HasValue)
            {
                // new report
                MarriageCertificateType selectedType;
                if (ComboBoxMarriageCertificateTypes.SelectedItem != null)
                    selectedType = (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem;
                else
                    selectedType = (MarriageCertificateType)ComboBoxMarriageCertificateTypes.Items[0];

                allLanguages = templateService.GetAvailableLanguagesForReportDefinition(selectedType);
                ComboBoxAllLanguages.ItemsSource = allLanguages;
            }

            SetCertificateLanguages();
        }

        private void ComboBoxMarriageCertificateLanguages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ComboBoxMarriageCertificateLanguages.SelectedItem != null && ComboBoxMarriageCertificateTypes.SelectedItem != null)
            {
                var language = (ValueIdPair)ComboBoxMarriageCertificateLanguages.SelectedItem;
                var type = (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem;

                Model = templateService.GetMarriageCertificate(type, language);

                DeleteButton.IsEnabled = IsDeleteableLanguage(language);
            }
        }

        private static bool IsDeleteableLanguage(ValueIdPair selectedLanguage)
        {
            if (selectedLanguage.Name.ToLower().Equals("svenska") || selectedLanguage.Name.ToLower().Equals("engelska"))
            {
                return false;
            }
            return true;
        }

        private void SetCertificateLanguages()
        {
            if (ComboBoxMarriageCertificateTypes.SelectedItem != null)
            {
                if (ComboBoxMarriageCertificateLanguages.Visibility == Visibility.Visible)
                {
                    var type = (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem;
                    certificateLanguages = templateService.GetLanguagesForCertificateType(type);
                    ComboBoxMarriageCertificateLanguages.ItemsSource = certificateLanguages;
                }
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (model != null)
            {
                if (ComboBoxMarriageCertificateLanguages.Visibility == Visibility.Visible)
                {
                    TextBoxHeading.Text = model.Heading;
                    TextBoxInception.Text = model.Inception;
                    TextBoxBetweenNames.Text = model.BetweenNames;
                    TextBoxAboveDate.Text = model.AboveDate;
                    TextBoxCity.Text = model.City;
                    TextBoxBelowDate.Text = model.BelowDate;
                    TextBoxSignLine.Text = model.SignLine;
                    TextBoxBelowSignature.Text = model.BelowSignature;

                    //ToggleButtons();                    
                }
                else
                {
                    ComboBoxMarriageCertificateLanguages.Visibility = Visibility.Visible;
                    ComboBoxAllLanguages.Visibility = Visibility.Hidden;
                    SetCertificateLanguages();

                    var language = (ValueIdPair)ComboBoxMarriageCertificateLanguages.Items[0];
                    MarriageCertificateType type;

                    if (ComboBoxMarriageCertificateTypes.SelectedItem != null)
                        type = (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem;
                    else
                        type = MarriageCertificateType.Wedding;

                    Model = templateService.GetMarriageCertificate(type, language);
                }
            }

            DeleteButton.IsEnabled = false;
            CancelButton.IsEnabled = false;
            SaveButton.IsEnabled = false;
            e.Handled = true;
        }

        private bool CanSave()
        {
            bool canSave = false;

            if (ComboBoxAllLanguages.Visibility == Visibility.Visible)
                canSave = ComboBoxAllLanguages.SelectedItem != null ? true : false || canSave;

            if (ComboBoxMarriageCertificateLanguages.Visibility == Visibility.Visible)
                canSave = ComboBoxMarriageCertificateLanguages.SelectedItem != null ? true : false || canSave;

            canSave = ComboBoxMarriageCertificateTypes.SelectedItem != null ? true : false || canSave;

            return canSave;
        }
        
        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if(!CanSave())
            {
                string message = string.Empty;
                if (ComboBoxMarriageCertificateTypes.SelectedItem == null)
                    message = "Du måste ange typ vigsel eller partnerskap";

                if (ComboBoxMarriageCertificateLanguages.SelectedItem == null)
                    message = "Du måste ange ett språk";

                MessageBox.Show(message, "Information", MessageBoxButton.OKCancel, MessageBoxImage.Information);
                model.ShouldSave = false;
            }
            else
            {
                BindingExpression be = TextBoxHeading.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxInception.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxBetweenNames.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxAboveDate.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxCity.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxBelowDate.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxSignLine.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                be = TextBoxBelowSignature.GetBindingExpression(TextBox.TextProperty);
                be.UpdateSource();

                if (ComboBoxAllLanguages.Visibility == Visibility.Visible)
                    model.SelectedLanguage = (ValueIdPair) ComboBoxAllLanguages.SelectedItem;
                else
                    model.SelectedLanguage = (ValueIdPair)ComboBoxMarriageCertificateLanguages.SelectedItem;

                model.SelectedMarriageCertificateType =
                    (MarriageCertificateType) ComboBoxMarriageCertificateTypes.SelectedItem;

                model.ShouldSave = true;

                SaveButton.IsEnabled = false;
                CancelButton.IsEnabled = false;
                DeleteButton.IsEnabled = false;

                ComboBoxMarriageCertificateLanguages.Visibility = Visibility.Visible;
                ComboBoxAllLanguages.Visibility = Visibility.Hidden;
            }
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            MarriageCertificateType selectedType;
            if (ComboBoxMarriageCertificateTypes.SelectedItem != null)
                selectedType = (MarriageCertificateType)ComboBoxMarriageCertificateTypes.SelectedItem;
            else
                selectedType = (MarriageCertificateType) ComboBoxMarriageCertificateTypes.Items[0];
            
            allLanguages = templateService.GetAvailableLanguagesForReportDefinition(selectedType);
            ComboBoxAllLanguages.ItemsSource = allLanguages;

            ComboBoxMarriageCertificateLanguages.Visibility = Visibility.Hidden;
            ComboBoxAllLanguages.Visibility = Visibility.Visible;
            CancelButton.IsEnabled = true;
            Model = templateService.AddNewMarriageCertificate();

            SaveButton.IsEnabled = false;
            CancelButton.IsEnabled = true;
            DeleteButton.IsEnabled = false;
        }

        private void TextBoxHeading_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            var textBox = (TextBox)sender;

            if (textBox != null)
            {
                SaveButton.IsEnabled = true;
                CancelButton.IsEnabled = true;
            }
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            SaveButton.IsEnabled = false;
            CancelButton.IsEnabled = false;
            DeleteButton.IsEnabled = false;
        }
    }
}
